import java.util.concurrent.TimeUnit;

/**
 * wait和sleep释放锁行为的区别
 */
public class WaitSleepDemo8 {
    public static void main(String[] args) throws InterruptedException {
        Object lock=new Object();
        Object lock2=new Object();
        Thread t1=new Thread(()->{
            synchronized (lock){
                System.out.println("线程1：开始执行");
                try {
                    lock.wait(3*1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程1：结束执行");
            }
        },"wait(0)");
        t1.start();

        Thread t2=new Thread(()->{
            synchronized (lock2){
                System.out.println("线程2：开始执行 ");
                try {
                    Thread.sleep(3*1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程2：结束执行 ");
            }
        },"sleep(0)");
        t2.start();

        //创建两个线程，先让线程休眠1s之后，尝试获取，看能不能获取到锁
        //如果可以获取到锁，说明休眠时线程是释放锁的，而如果获取不到锁，说明是不释放锁
        Thread t3=new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("尝试获取wait方法的锁");
            synchronized (lock){
                System.out.println("成功获取wait锁");
            }
        },"wait2");
        t3.start();

        Thread t4=new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("尝试获取sleep方法的锁");
            synchronized (lock2){
                System.out.println("成功获取sleep锁");
            }
        },"sleep2");
        t4.start();
    }
}
